package com.atguigu.windowFunction;

import com.atguigu.bean.OrderEvent;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * Created by RUI on 2021/6/18 16:28
 *
 * 订单支付实时监控
 */
public class High_prj_OrderWatch {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        // 创建WatermarkStrategy
        WatermarkStrategy<OrderEvent> wms = WatermarkStrategy
            .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(20))
            .withTimestampAssigner((element, recordTimestamp) -> element.getEventTime());
        env
            .readTextFile("input/OrderLog.csv")
            .map(line -> {
                String[] datas = line.split(",");
                return new OrderEvent(
                    Long.valueOf(datas[0]),
                    datas[1],
                    datas[2],
                    Long.parseLong(datas[3]) * 1000);

            })
            .assignTimestampsAndWatermarks(wms)
            .keyBy(OrderEvent::getOrderId)
            .process(new KeyedProcessFunction<Long, OrderEvent, String>() {

                private ValueState<OrderEvent> createState;
                private ValueState<OrderEvent> payState;

                @Override
                public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                    // 定时器触发表示只有一个
                    if(createState.value() !=null){
                        out.collect(createState.value().getOrderId() + " 只有创建订单没有支付订单....");
                    }else{
                        out.collect(payState.value().getOrderId() + " 只有支付没有创建, 检测系统漏洞....");
                    }
                }

                @Override
                public void open(Configuration parameters) throws Exception {

                    createState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                    payState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("payState", OrderEvent.class));

                }

                @Override
                public void processElement(OrderEvent value, Context ctx, Collector<String> out) throws Exception {

                    // 处理只有一个状态的情况
                    // 每个key的第一条数据过来的 时候, 注册定时器
                    if (null == createState.value() && null == payState.value()) {
                        ctx.timerService().registerEventTimeTimer(value.getEventTime() + 30 * 60 * 1000);
                    } else {
                        OrderEvent event = payState.value() == null ? createState.value() : payState.value();
                        ctx.timerService().deleteEventTimeTimer(event.getEventTime() + 30 * 60 * 1000);
                    }

                    //如果这次是pay, 应该去状态中查找是否有对应的create, 如果有正常
                    //如果没有 把这个pay信息存储到状态中
                    String eventType = value.getEventType();
                    if ("create".equals(eventType)) {
                        if (null == payState.value()) {
                            createState.update(value);
                        } else if (payState.value().getEventTime() - value.getEventTime() < 30 * 60 * 1000) {
//                            out.collect(value.getOrderId()+ " 订单正常");
                        } else {
                            out.collect(value.getOrderId()+" 订单异常，订单被超时支付");
                        }
                    } else if ("pay".equals(eventType)) {
                        if (null == createState.value()) {
                            payState.update(value);
                        } else if (value.getEventTime() - createState.value().getEventTime() < 30 * 60 * 1000) {
//                            out.collect(value.getOrderId()+" 订单正常");
                        } else {
                            out.collect(value.getOrderId()+" 订单异常，订单被超时支付");
                        }
                    }

                }
            })

            .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
